package com.github.lee.unsplash.ui.auth

import android.content.Context
import android.graphics.Color
import android.net.Uri
import android.widget.Toast
import androidx.activity.viewModels
import androidx.appcompat.widget.Toolbar
import androidx.core.content.ContextCompat
import com.github.lee.core.common.ext.log
import com.github.lee.core.common.normalIntent
import com.github.lee.mvvm.core.ui.web.BaseWebViewActivity
import com.github.lee.mvvm.core.ui.web.CustomizeWebViewClient
import com.github.lee.mvvm.core.ui.web.WebHandler
import com.github.lee.unsplash.BuildConfig
import com.github.lee.unsplash.R
import com.github.lee.unsplash.databinding.ToolbarCenterTitleBinding
import com.github.lee.unsplash.manager.LoginManager
import com.tencent.smtt.export.external.interfaces.WebResourceRequest
import com.tencent.smtt.sdk.WebView
import dagger.hilt.android.AndroidEntryPoint

enum class Scope constructor(private val value: String) {
    /**默认。读取公共数据*/
    PUBLIC("public"),

    /**访问用户的私人数据*/
    READ_USER("read_user"),

    /**更新用户的个人资料*/
    WRITE_USER("write_user"),

    /**从用户的照片中读取私人数据*/
    READ_PHOTOS("read_photos"),

    /**代表用户更新照片*/
    WRITE_PHOTOS("write_photos"),

    /**代表用户喜欢或不喜欢照片*/
    WRITE_LIKES("write_likes"),

    /**代表用户关注或取消关注用户*/
    WRITE_FOLLOWERS("write_followers"),

    /**查看用户的私人收藏*/
    READ_COLLECTIONS("read_collections"),

    /**创建和更新用户的收藏集*/
    WRITE_COLLECTIONS("write_collections");

    companion object {
        fun all(): String {
            val sb = StringBuilder()
            for ((index, item) in values().withIndex()) {
                sb.append(item.value)
                if (index < values().size - 1) {
                    sb.append("+")
                }
            }
            return sb.toString()
        }
    }

}

@AndroidEntryPoint
class WebAuthActivity : BaseWebViewActivity<WebAuthVM>() {

    companion object {
        fun start(context: Context) {
            context.startActivity(normalIntent(context, WebAuthActivity::class.java))
        }
    }
    //===Desc:=========================================================

    override fun onCreateViewModel(): WebAuthVM = viewModels<WebAuthVM>().value

    override fun getLoadUrl(): String {
        val clientId = BuildConfig.API_KEY
        val redirectUri = "urn:ietf:wg:oauth:2.0:oob"
        val scope = Scope.all()
        return "https://unsplash.com/oauth/authorize?client_id=${clientId}&redirect_uri=${redirectUri}&response_type=code&scope=${scope}"
    }

    override fun onCreateToolbar(): Toolbar =
        ToolbarCenterTitleBinding.inflate(layoutInflater)
            .also {
                it.navigationIcon = ContextCompat.getDrawable(mContext, R.mipmap.ic_arrow_back_gray)
                it.navigationClick = { onBackPressed() }
                it.title = getString(R.string.txt_user_login)
            }
            .tlToolbar.also {
                it.title = ""
            }

    override fun onCreateWebViewClient(webHandler: WebHandler): CustomizeWebViewClient? {
        return object : CustomizeWebViewClient(webHandler) {
            // >=7.0
            override fun shouldOverrideUrlLoading(
                wv: WebView?,
                request: WebResourceRequest?
            ): Boolean {
                val host = request?.url?.host
                val path = request?.url?.path
                val code = request?.url?.getQueryParameter("code")
                log("host = $host , path = $path,code = $code")
                if (code.isNullOrEmpty()) {
                    wv?.loadUrl(request?.url?.toString())
                } else {
                    //获取token
                    pageVM.getAuthToken(code)
                }
                return true

            }

            override fun shouldOverrideUrlLoading(wv: WebView?, url: String?): Boolean {
                wv?.loadUrl(url)
                val uri = Uri.parse(url)
                val host = uri?.host
                val path = uri?.path
                val code = uri?.getQueryParameter("code")
                log("host = $host , path = $path,code = $code")
                if (code.isNullOrEmpty()) {
                    wv?.loadUrl(url)
                } else {
                    //获取token
                    pageVM.getAuthToken(code)
                }
                return true
            }
        }
    }
    //===Desc:=========================================================


    override fun onObserveData() {
        super.onObserveData()
        LoginManager.loginSuccessLiveData.observe(this) {
            if (it) {
                Toast.makeText(mContext, R.string.txt_login_success, Toast.LENGTH_SHORT).show()
                finish()
            }
        }
    }

    override fun onSetViewData() {
        super.onSetViewData()
        setStatusBarColor(Color.WHITE)
        changeStatusBarTextColor(true)
    }

}